package com.travel.server.manager.impl.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.travel.common.CommonConstant;
import com.travel.common.util.CollectionUtil;
import com.travel.common.util.CommonUtil;
import com.travel.common.util.DateUtil;
import com.travel.server.manager.impl.command.BaseImportCommand;
import com.travel.server.manager.impl.dal.OrderDal;
import com.travel.server.manager.impl.youzan.*;
import com.travel.server.manager.model.CustomerInfo;
import com.travel.server.manager.model.OrderInfo;
import com.travel.server.manager.model.ProjectInfo;
import com.travel.server.manager.model.ProjectSpecial;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanItemGetResult;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanUsersWeixinFollowerGetResult;
import com.youzan.open.sdk.gen.v4_0_0.model.YouzanTradeGetResult;
import com.youzan.open.sdk.gen.v4_0_0.model.YouzanTradesSoldGetResult;
import com.youzan.open.sdk.gen.v4_0_0.model.YouzanTradesSoldGetResult.StructurizationTrade;
import com.youzan.open.sdk.gen.v4_0_0.model.YouzanTradesSoldGetResult.StructurizationTradeOrderInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018/12/3 16:36
 * @Desc:
 */
@Component
@Slf4j
public class YouzanOrderTask extends BaseImportCommand {

    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");

    private static final long pageNo = 100;

    @Autowired
    private OrderDal orderDal;

    public void handle(){
        Date now = new Date();
        for(YouzanStateEnum stateEnum : YouzanStateEnum.values()) {
            long page = 0;
            Date startTime = DateUtil.get(now, 0, 0, 0, 0);
            Date endTime = DateUtil.get(now, 23, 59, 59, 999);
            Long total = null;
            while(total == null || total > pageNo) {
                YouzanTradesSoldGetResult result = YouzanSal.queryOrderList(stateEnum.getStatus(), startTime, endTime, ++page, pageNo);
                total = result.getTotalResults();
                StructurizationTrade[] tradeArray = result.getFullOrderInfoList();
                importOrder(tradeArray, stateEnum.getOrderState());
            }
        }
    }

    private void importOrder(StructurizationTrade[] tradeArray, String orderState){
        Date now = new Date();
        if(tradeArray != null && tradeArray.length > 0){
            List<String> tidList = new ArrayList<>();
            for(StructurizationTrade trade : tradeArray){
                StructurizationTradeOrderInfo tradeInfo = trade.getFullOrderInfo();
                tidList.add(tradeInfo.getOrderInfo().getTid());
            }
            //获取订单信息
            List<OrderInfo> orderList = new ArrayList<>();
            for(String tid : tidList){
                YouzanTradeGetResult result = YouzanSal.queryOrder(tid);
                YouzanTradeGetResult.StructurizationTradeOrderInfo fullOrderInfo = result.getFullOrderInfo();
                YouzanTradeGetResult.StructurizationTradeItemDetail[] tradeItemDetailArray = fullOrderInfo.getOrders();
                //有多个商品记录，就拆分成多个订单
                for(YouzanTradeGetResult.StructurizationTradeItemDetail detail : tradeItemDetailArray){
                    Long itemId = detail.getItemId();
                    //查询商品信息，查询本地项目信息+项目规格（出行日期）
                    YouzanItemGetResult itemGetResult = YouzanSal.queryItem(itemId);
                    String itemNo = itemGetResult.getItem().getItemNo();
                    if(StringUtils.isBlank(itemNo)){
                        continue;
                    }
                    ProjectInfo projectInfo = projectDal.selectByNumber(itemNo);
                    if(projectInfo == null){
                        log.info("未查询到项目信息, number {}, itemId {}, tid {}", itemNo, itemId, tid);
                        continue;
                    }
                    OrderInfo orderInfo = makeOrderInfo();
                    orderInfo.setOrderId(tid);
                    orderInfo.setOrderTime(fullOrderInfo.getOrderInfo().getCreated());
                    orderInfo.setPayAmount(CommonUtil.yuanToFen(new BigDecimal(fullOrderInfo.getPayInfo().getPayment() + "")).longValue());
                    orderInfo.setOrderState(orderState);
                    orderInfo.setOrderType(YouzanItemTypeEnum.getDescByType(detail.getItemType()));
                    orderInfo.setPayType(YouzanPayTypeEnum.getDescByType(fullOrderInfo.getOrderInfo().getPayType()));
                    orderInfo.setNote(fullOrderInfo.getRemarkInfo().getTradeMemo());
                    orderInfo.setDistributeType(YouzanExpressTypeEnum.getDescByType(fullOrderInfo.getOrderInfo().getExpressType()));
                    orderInfo.setCollectName(fullOrderInfo.getAddressInfo().getReceiverName());
                    orderInfo.setCollectMobile(fullOrderInfo.getAddressInfo().getReceiverTel());
                    orderInfo.setCollectAddress(fullOrderInfo.getAddressInfo().getDeliveryAddress());
                    orderInfo.setBuyerMessage(fullOrderInfo.getRemarkInfo().getBuyerMessage());
                    String[] outerTransactions = fullOrderInfo.getPayInfo().getOuterTransactions();
                    if(outerTransactions != null && outerTransactions.length > 0) {
                        orderInfo.setOutOrderId(outerTransactions[0]);
                    }
                    String[] transaction = fullOrderInfo.getPayInfo().getTransaction();
                    if(transaction != null && transaction.length > 0) {
                        orderInfo.setPayId(transaction[0]);
                    }
                    Long fansId = fullOrderInfo.getBuyerInfo().getFansId();
                    CustomerInfo customerInfo = queryCustomer(orderInfo.getCollectName(), orderInfo.getCollectMobile());
                    Integer customerId;
                    if(customerInfo == null) {
                        YouzanUsersWeixinFollowerGetResult userResult = YouzanSal.queryUser(fansId);
                        customerInfo = new CustomerInfo();
                        customerInfo.setBeCustomerTime(userResult.getUser().getFollowTime());
                        customerInfo.setWechatNick(userResult.getUser().getNick());
                        customerInfo.setCreateTime(now);
                        customerInfo.setUpdateTime(now);
                        customerInfo.setCreateBy("System");
                        customerInfo.setUpdateBy("System");
                        if(userResult.getUser().getPoints() != null){
                            customerInfo.setAvailableScores(userResult.getUser().getPoints() + "");
                        }
                        customerInfo.setState(CommonConstant.YES);
                        customerDal.insertOrUpdate(customerInfo);
                    }
                    customerId = customerInfo.getId();
                    orderInfo.setCustomerId(customerId);
                    String skuPropertiesNameStr = detail.getSkuPropertiesName();
                    if(StringUtils.isBlank(skuPropertiesNameStr)){
                        log.info("未配置skuPropertiesName信息");
                    }else {
                        JSONArray array = JSONArray.parseArray(skuPropertiesNameStr);
                        for (int i = 0; i < array.size(); i++) {
                            JSONObject item = array.getJSONObject(i);
                            if ("出行日期".equals(item.getString("k"))) {
                                String travelDateStr = item.getString("v");
                                if (StringUtils.isBlank(travelDateStr)) {
                                    log.info("出行日期value为空");break;
                                }else {
                                    String dateStr = StringUtils.split(travelDateStr, "-")[0];
                                    Date travelDate;
                                    try {
                                        travelDate = sdf.parse(travelDateStr);
                                    } catch (Exception e) {
                                        log.error("转换出行日期异常：", e);
                                        log.info("无法转换出行日期, dateStr {}", dateStr);
                                        break;
                                    }
                                    travelDate = DateUtil.setDayStart(travelDate);
                                    ProjectSpecial projectSpecial = specialDal.select(projectInfo.getId(), travelDate);
                                    if (projectSpecial == null) {
                                        log.info("未查询到出行日期记录, projectId {}, travelDate{}", projectInfo.getId(), DateUtil.YYYY_MM_DD.format(travelDate));
                                        break;
                                    }
                                    orderInfo.setSpecialId(projectSpecial.getId());
                                }
                            }
                        }
                    }
                    orderList.add(orderInfo);
                }
            }
            if(!CollectionUtil.isEmpty(orderList)){
                orderDal.batchInsert(orderList);
            }
        }
    }

    private OrderInfo makeOrderInfo(){
        Date now = new Date();
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateBy("System");
        orderInfo.setUpdateBy("System");
        orderInfo.setCreateTime(now);
        orderInfo.setUpdateTime(now);
        return orderInfo;
    }
}
